﻿window.drawWafer = (waferAngleInDegrees, shots, shotWidth, shotHeight, dotNetObjectReference) => {
    const canvas = document.getElementById('waferCanvas');
    const ctx = canvas.getContext('2d');

    // 清除之前的画布内容
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 放大倍数
    const scaleFactor = 1.8;

    // 调整晶圆半径并放大
    const waferRadius = 150 * scaleFactor;
    const waferCenterX = 200 * scaleFactor;
    const waferCenterY = canvas.height - 200 * scaleFactor;

    // 放大 Shot 宽高
    const scaledShotWidth = shotWidth * scaleFactor;
    const scaledShotHeight = shotHeight * scaleFactor;

    // 绘制完整晶圆，保留上半部分和两侧
    ctx.beginPath();
    ctx.arc(waferCenterX, waferCenterY, waferRadius, 0, 2 * Math.PI); // 完整的圆
    ctx.strokeStyle = '#888';
    ctx.lineWidth = 2;
    ctx.stroke();

    // 将传入的角度转换为弧度
    const waferAngleInRadians = -waferAngleInDegrees * (Math.PI / 180);

    // notch 参数
    const notchWidth = 10 * scaleFactor;  // Notch 的宽度
    const notchHeight = 5 * scaleFactor;  // Notch 的高度
    const notchRadius = waferRadius;      // Notch 位于晶圆边缘
    const notchOffsetY = notchHeight;     // Notch 的垂直偏移

    // 保存当前画布状态
    ctx.save();

    // 移动坐标系到晶圆的中心
    ctx.translate(waferCenterX, waferCenterY);

    // 根据传入的角度旋转坐标系
    ctx.rotate(waferAngleInRadians);

    // 绘制 notch （凹槽），位于旋转后的底部
    const notchCenterY = notchRadius; // Notch 位于晶圆边缘，向下凹陷

    ctx.beginPath();
    ctx.arc(0, notchCenterY, notchHeight, Math.PI, 2 * Math.PI); // notch 半圆弧

    // 设置填充颜色
    ctx.fillStyle = 'black'; // Notch 的填充颜色
    ctx.fill(); // 填充路径

    ctx.strokeStyle = 'black'; // Notch 的颜色
    ctx.lineWidth = 2;
    ctx.stroke();

    // 恢复画布到初始状态
    ctx.restore();


    // 绘制 Shots
    shots.forEach(shot => {
        let flippedY = canvas.height - shot.displayY * scaleFactor;

        // 设置颜色
        ctx.fillStyle = shot.fillColor;
        ctx.strokeStyle = 'black';
        ctx.lineWidth = 1;

        // 检查Shot是否在圆内
        const distanceFromCenter = Math.sqrt(
            Math.pow((shot.displayX * scaleFactor) - waferCenterX, 2) +
            Math.pow(flippedY - waferCenterY, 2)
        );

        if (distanceFromCenter <= waferRadius) {

            // 绘制圆角矩形，放大后的尺寸
            drawRoundedRect(ctx, shot.displayX * scaleFactor - scaledShotWidth / 2, flippedY - scaledShotHeight / 2, scaledShotWidth, scaledShotHeight, 5);

            // 绘制网格坐标
            ctx.fillStyle = 'black';
            ctx.font = `${10 * scaleFactor}px Arial`;
            ctx.textAlign = 'center';
            ctx.fillText(`${shot.gridX},${shot.gridY}`, shot.displayX * scaleFactor, flippedY);
        }
    });

    // 绘制图例
    drawLegend(ctx, canvas.width - 150, 40);

    // 移除原来点击事件监听器
    canvas.removeEventListener('click', canvas.handleCanvasClickRef);

    // 创建新的事件处理函数并保存引用
    canvas.handleCanvasClickRef = createHandleCanvasClick(shots, scaleFactor, scaledShotWidth, scaledShotHeight, dotNetObjectReference);

    // 添加新的点击事件监听器
    canvas.addEventListener('click', canvas.handleCanvasClickRef);

};

// Helper function to draw rounded rectangles
function drawRoundedRect(ctx, x, y, width, height, radius) {
    ctx.beginPath();
    ctx.moveTo(x + radius, y);
    ctx.arcTo(x + width, y, x + width, y + height, radius);
    ctx.arcTo(x + width, y + height, x, y + height, radius);
    ctx.arcTo(x, y + height, x, y, radius);
    ctx.arcTo(x, y, x + width, y, radius);
    ctx.fill();
    ctx.stroke();
}

// Function to draw the legend
function drawLegend(ctx, x, y) {
    // 绘制图例背景
    ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
    ctx.fillRect(x, y, 130, 100);

    ctx.strokeStyle = 'black';
    ctx.strokeRect(x, y, 130, 100);

    // 图例标题
    ctx.fillStyle = 'black';
    ctx.font = '14px Arial';
    ctx.fillText('Legend', x + 65, y + 20);

    // 绘制不同 shot 类型的颜色和说明
    const legendData = [
        { color: '#FFC0CB', label: 'MarkAlignment' },
        { color: '#87CEEB', label: 'Measuring' },
        { color: '#008000', label: 'Measured' }
    ];

    // 绘制每个条目
    legendData.forEach((item, index) => {
        const itemY = y + 40 + index * 20;

        // 颜色方块
        ctx.fillStyle = item.color;
        ctx.fillRect(x + 10, itemY - 10, 15, 15);

        // 文字说明
        ctx.fillStyle = 'black';
        ctx.font = '12px Arial';
        ctx.fillText(item.label, x + 70, itemY);
    });
}

//闭包传递参数
function createHandleCanvasClick(shots, scaleFactor, scaledShotWidth, scaledShotHeight, dotNetObjectReference) {
    return function (event) {
        handleCanvasClick(event, shots, scaleFactor, scaledShotWidth, scaledShotHeight, dotNetObjectReference);
    };
}

// 定义新的点击事件处理器
const handleCanvasClick = (event, shots, scaleFactor, scaledShotWidth, scaledShotHeight, dotNetObjectReference) => {
    const canvas = document.getElementById('waferCanvas');
    const rect = canvas.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    // 遍历所有 shots，检查是否点击到了某个 shot
    shots.forEach(shot => {
        let flippedY = canvas.height - shot.displayY * scaleFactor;
        const shotX = shot.displayX * scaleFactor;
        const shotY = flippedY;

        // 检查点击是否在某个 Shot 的范围内
        if (x >= shotX - scaledShotWidth / 2 && x <= shotX + scaledShotWidth / 2 &&
            y >= shotY - scaledShotHeight / 2 && y <= shotY + scaledShotHeight / 2) {
            // 调用 Blazor 方法，传递 shot 信息
            dotNetObjectReference.invokeMethodAsync('OnShotClick', shot.gridX, shot.gridY);
        }
    });
};